<?php
// 缴费记录查看页面
header('Content-Type: text/html; charset=utf-8');

// 数据库连接配置
$config = [
    'type' => 'mysql',
    'hostname' => '127.0.0.1',
    'database' => 'dev002_gxyusheng',
    'username' => 'root',
    'password' => '159456',
    'charset' => 'utf8mb4',
    'prefix' => 'fa_'
];

try {
    // 创建数据库连接
    $dsn = "{$config['type']}:host={$config['hostname']};dbname={$config['database']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['username'], $config['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
    ]);

    // 获取筛选参数
    $statusFilter = $_GET['status'] ?? 'paid';  // 默认显示已支付
    $startDate = $_GET['start_date'] ?? '';  // 默认不选日期
    
    // 检查是否是清除日期操作
    $isClearDate = isset($_GET['clear_date']) && $_GET['clear_date'] == '1';
    
    // 构建SQL查询条件
    $whereConditions = [];
    $params = [];
    
    // 日期筛选条件 - 如果选择了日期才添加
    if (!empty($startDate)) {
        $whereConditions[] = "f.create_time >= :start_date";
        $params[':start_date'] = $startDate;
    }
    
    // 状态筛选条件
    if ($statusFilter === 'paid') {
        $whereConditions[] = "(o.pay_status = 1 AND o.refund_status is null)";
    } elseif ($statusFilter === 'waiting') {
        $whereConditions[] = "f.status = 0";
    } elseif ($statusFilter === 'refunded') {
        $whereConditions[] = "(o.refund_status = 1 OR o.pay_status = 4)";
    } else {
        // 显示全部状态（已支付、未缴费、过期未缴费、退款）
        $whereConditions[] = "(o.pay_status = 1 OR o.pay_status = 4 OR f.status = 0 OR f.status = 5)";
    }
    
    // 日期筛选条件已经在基础条件中添加
    
    // 执行查询 - 包含多种状态：已支付、未缴费、过期未缴费、退款
    $sql = "SELECT 
                f.intro, 
                c.name as class_name, 
                u.nickname, 
                u.username, 
                u.mobile, 
                f.table_id, 
                f.amount, 
                f.create_time, 
                o.pay_status, 
                o.refund_status, 
                o.refund_amount,
                f.status as form_status
            FROM `eb_apply_form_item` as f 
            LEFT JOIN fa_user u ON f.user_id = u.id 
            LEFT JOIN eb_classes c ON c.id = f.classes_id 
            LEFT JOIN fa_order o ON o.id = f.order_id 
            WHERE " . implode(" AND ", $whereConditions) . "
            ORDER BY f.create_time DESC";

    $stmt = $pdo->prepare($sql);
    
    // 绑定参数
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    
    $stmt->execute();
    $records = $stmt->fetchAll();

    // 计算统计数据 - 需要查询所有符合条件的记录，不限于当前筛选状态
    $statsSql = "SELECT 
                    f.amount, 
                    o.pay_status, 
                    o.refund_status, 
                    o.refund_amount,
                    f.status as form_status,
                    f.user_id,
                    f.create_time
                FROM `eb_apply_form_item` as f 
                LEFT JOIN fa_order o ON o.id = f.order_id 
                WHERE (o.pay_status = 1 OR o.pay_status = 4 OR f.status = 0 OR f.status = 5)";
    
    // 如果选择了日期，添加日期条件
    if (!empty($startDate)) {
        $statsSql .= " AND f.create_time >= :start_date";
    }
    
    $statsStmt = $pdo->prepare($statsSql);
    if (!empty($startDate)) {
        $statsStmt->bindValue(':start_date', $startDate);
    }
    $statsStmt->execute();
    $allRecords = $statsStmt->fetchAll();
    
    // 查询当日报名人数和缴费人数（同一个用户只算一个）
    // 如果用户选择了日期，则使用该日期；否则使用当前日期
    // 如果是清除日期操作，则使用当前日期进行当日统计
    $targetDate = (!empty($startDate) && !$isClearDate) ? $startDate : date('Y-m-d');
    $todaySignupSql = "SELECT COUNT(DISTINCT user_id) as count 
                       FROM `eb_apply_form_item` 
                       WHERE DATE(create_time) = :today";
    $todaySignupStmt = $pdo->prepare($todaySignupSql);
    $todaySignupStmt->bindValue(':today', $targetDate);
    $todaySignupStmt->execute();
    $todaySignupCount = $todaySignupStmt->fetch()['count'];
    
    // 独立总计统计（不受任何筛选条件影响）
    // 总缴费金额
    $totalPaidAmountSql = "SELECT SUM(o.amount) as total_amount 
                          FROM `eb_apply_form_item` as f 
                          LEFT JOIN fa_order o ON o.id = f.order_id 
                          WHERE o.pay_status = 1 AND o.refund_status IS NULL";
    $totalPaidAmountStmt = $pdo->prepare($totalPaidAmountSql);
    $totalPaidAmountStmt->execute();
    $totalPaidAmount = $totalPaidAmountStmt->fetch()['total_amount'] ?? 0;
    
    // 已支付笔数
    $totalPaidCountSql = "SELECT COUNT(*) as count 
                         FROM `eb_apply_form_item` as f 
                         LEFT JOIN fa_order o ON o.id = f.order_id 
                         WHERE o.pay_status = 1 AND o.refund_status IS NULL";
    $totalPaidCountStmt = $pdo->prepare($totalPaidCountSql);
    $totalPaidCountStmt->execute();
    $totalPaidCount = $totalPaidCountStmt->fetch()['count'] ?? 0;
    
    // 未缴费笔数
    $totalWaitingCountSql = "SELECT COUNT(*) as count 
                            FROM `eb_apply_form_item` as f 
                            LEFT JOIN fa_order o ON o.id = f.order_id 
                            WHERE f.status = 0";
    $totalWaitingCountStmt = $pdo->prepare($totalWaitingCountSql);
    $totalWaitingCountStmt->execute();
    $totalWaitingCount = $totalWaitingCountStmt->fetch()['count'] ?? 0;
    
    // 过期未缴笔数
    $totalExpiredCountSql = "SELECT COUNT(*) as count 
                             FROM `eb_apply_form_item` as f 
                             LEFT JOIN fa_order o ON o.id = f.order_id 
                             WHERE f.status = 5";
    $totalExpiredCountStmt = $pdo->prepare($totalExpiredCountSql);
    $totalExpiredCountStmt->execute();
    $totalExpiredCount = $totalExpiredCountStmt->fetch()['count'] ?? 0;
    
    // 已退款笔数
    $totalRefundedCountSql = "SELECT COUNT(*) as count 
                             FROM `eb_apply_form_item` as f 
                             LEFT JOIN fa_order o ON o.id = f.order_id 
                             WHERE o.refund_status = 1 OR o.pay_status = 4";
    $totalRefundedCountStmt = $pdo->prepare($totalRefundedCountSql);
    $totalRefundedCountStmt->execute();
    $totalRefundedCount = $totalRefundedCountStmt->fetch()['count'] ?? 0;
    
    // 总记录笔数
    $totalRecordsCountSql = "SELECT COUNT(*) as count 
                            FROM `eb_apply_form_item` as f 
                            LEFT JOIN fa_order o ON o.id = f.order_id";
    $totalRecordsCountStmt = $pdo->prepare($totalRecordsCountSql);
    $totalRecordsCountStmt->execute();
    $totalRecordsCount = $totalRecordsCountStmt->fetch()['count'] ?? 0;
    
    // 总退款金额
    $totalRefundAmountSql = "SELECT SUM(o.refund_amount) as total_refund 
                            FROM `eb_apply_form_item` as f 
                            LEFT JOIN fa_order o ON o.id = f.order_id 
                            WHERE o.refund_status = 1 OR o.pay_status = 4";
    $totalRefundAmountStmt = $pdo->prepare($totalRefundAmountSql);
    $totalRefundAmountStmt->execute();
    $totalRefundAmount = $totalRefundAmountStmt->fetch()['total_refund'] ?? 0;
    
    $todayPaidSql = "SELECT COUNT(DISTINCT f.user_id) as count 
                     FROM `eb_apply_form_item` as f 
                     LEFT JOIN fa_order o ON o.id = f.order_id 
                     WHERE DATE(f.create_time) = :today 
                     AND o.pay_status = 1 
                     AND o.refund_status is null";
    $todayPaidStmt = $pdo->prepare($todayPaidSql);
    $todayPaidStmt->bindValue(':today', $targetDate);
    $todayPaidStmt->execute();
    $todayPaidCount = $todayPaidStmt->fetch()['count'];
    
    // 新增：当日缴费金额统计
    $todayPaidAmountSql = "SELECT SUM(o.amount) as total_amount 
                           FROM `eb_apply_form_item` as f 
                           LEFT JOIN fa_order o ON o.id = f.order_id 
                           WHERE DATE(f.create_time) = :today 
                           AND o.pay_status = 1 
                           AND o.refund_status is null";
    $todayPaidAmountStmt = $pdo->prepare($todayPaidAmountSql);
    $todayPaidAmountStmt->bindValue(':today', $targetDate);
    $todayPaidAmountStmt->execute();
    $todayPaidAmount = $todayPaidAmountStmt->fetch()['total_amount'] ?? 0;
    
    // 新增：当日退费人数统计
    $todayRefundCountSql = "SELECT COUNT(DISTINCT f.user_id) as count 
                           FROM `eb_apply_form_item` as f 
                           LEFT JOIN fa_order o ON o.id = f.order_id 
                           WHERE DATE(f.create_time) = :today 
                           AND (o.refund_status = 1 OR o.pay_status = 4)";
    $todayRefundCountStmt = $pdo->prepare($todayRefundCountSql);
    $todayRefundCountStmt->bindValue(':today', $targetDate);
    $todayRefundCountStmt->execute();
    $todayRefundCount = $todayRefundCountStmt->fetch()['count'];
    
    // 新增：当日退费金额统计
    $todayRefundAmountSql = "SELECT SUM(o.refund_amount) as total_refund 
                            FROM `eb_apply_form_item` as f 
                            LEFT JOIN fa_order o ON o.id = f.order_id 
                            WHERE DATE(f.create_time) = :today 
                            AND (o.refund_status = 1 OR o.pay_status = 4)";
    $todayRefundAmountStmt = $pdo->prepare($todayRefundAmountSql);
    $todayRefundAmountStmt->bindValue(':today', $targetDate);
    $todayRefundAmountStmt->execute();
    $todayRefundAmount = $todayRefundAmountStmt->fetch()['total_refund'] ?? 0;
    
    // 获取最近10天的统计数据
    $last10DaysStats = [];
    for ($i = 9; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        
        // 报名人数（去重）
        $signupSql = "SELECT COUNT(DISTINCT user_id) as count 
                     FROM `eb_apply_form_item` 
                     WHERE DATE(create_time) = :date";
        $signupStmt = $pdo->prepare($signupSql);
        $signupStmt->bindValue(':date', $date);
        $signupStmt->execute();
        $signupCount = $signupStmt->fetch()['count'] ?? 0;
        
        // 缴费人数（去重）
        $paidSql = "SELECT COUNT(DISTINCT f.user_id) as count 
                   FROM `eb_apply_form_item` as f 
                   LEFT JOIN fa_order o ON o.id = f.order_id 
                   WHERE DATE(f.create_time) = :date 
                   AND o.pay_status = 1 
                   AND o.refund_status IS NULL";
        $paidStmt = $pdo->prepare($paidSql);
        $paidStmt->bindValue(':date', $date);
        $paidStmt->execute();
        $paidCount = $paidStmt->fetch()['count'] ?? 0;
        
        // 退费人数（去重）
        $refundSql = "SELECT COUNT(DISTINCT f.user_id) as count 
                     FROM `eb_apply_form_item` as f 
                     LEFT JOIN fa_order o ON o.id = f.order_id 
                     WHERE DATE(f.create_time) = :date 
                     AND (o.refund_status = 1 OR o.pay_status = 4)";
        $refundStmt = $pdo->prepare($refundSql);
        $refundStmt->bindValue(':date', $date);
        $refundStmt->execute();
        $refundCount = $refundStmt->fetch()['count'] ?? 0;
        
        // 报名金额
        $signupAmountSql = "SELECT SUM(amount) as total 
                           FROM `eb_apply_form_item` 
                           WHERE DATE(create_time) = :date";
        $signupAmountStmt = $pdo->prepare($signupAmountSql);
        $signupAmountStmt->bindValue(':date', $date);
        $signupAmountStmt->execute();
        $signupAmount = $signupAmountStmt->fetch()['total'] ?? 0;
        
        // 缴费金额
        $paidAmountSql = "SELECT SUM(o.amount) as total 
                         FROM `eb_apply_form_item` as f 
                         LEFT JOIN fa_order o ON o.id = f.order_id 
                         WHERE DATE(f.create_time) = :date 
                         AND o.pay_status = 1 
                         AND o.refund_status IS NULL";
        $paidAmountStmt = $pdo->prepare($paidAmountSql);
        $paidAmountStmt->bindValue(':date', $date);
        $paidAmountStmt->execute();
        $paidAmount = $paidAmountStmt->fetch()['total'] ?? 0;
        
        // 退费金额
        $refundAmountSql = "SELECT SUM(o.refund_amount) as total 
                           FROM `eb_apply_form_item` as f 
                           LEFT JOIN fa_order o ON o.id = f.order_id 
                           WHERE DATE(f.create_time) = :date 
                           AND (o.refund_status = 1 OR o.pay_status = 4)";
        $refundAmountStmt = $pdo->prepare($refundAmountSql);
        $refundAmountStmt->bindValue(':date', $date);
        $refundAmountStmt->execute();
        $refundAmount = $refundAmountStmt->fetch()['total'] ?? 0;
        
        $last10DaysStats[] = [
            'date' => $date,
            'signup_count' => $signupCount,
            'paid_count' => $paidCount,
            'refund_count' => $refundCount,
            'signup_amount' => $signupAmount,
            'paid_amount' => $paidAmount,
            'refund_amount' => $refundAmount
        ];
    }
    
    // 查询所有记录（不受日期筛选影响，只受状态筛选影响）
    $allStatsSql = "SELECT f.*, o.pay_status, o.refund_status, o.amount, o.refund_amount, f.status as form_status
                   FROM `eb_apply_form_item` as f 
                   LEFT JOIN fa_order o ON o.id = f.order_id 
                   WHERE 1=1";
    $allStatsParams = [];
    
    // 添加状态筛选条件
    if (!empty($statusFilter)) {
        if ($statusFilter === 'paid') {
            $allStatsSql .= " AND o.pay_status = 1 AND o.refund_status IS NULL";
        } elseif ($statusFilter === 'waiting') {
            $allStatsSql .= " AND f.status = 0";
        } elseif ($statusFilter === 'refunded') {
            $allStatsSql .= " AND (o.refund_status = 1 OR o.pay_status = 4)";
        }
    }
    
    $allStatsStmt = $pdo->prepare($allStatsSql);
    $allStatsStmt->execute($allStatsParams);
    $allStatsRecords = $allStatsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 初始化统计变量
    $totalAmount = 0;
    $totalRecords = 0;
    $totalRefund = 0;
    $totalPaid = 0;
    $totalWaiting = 0;
    $totalExpired = 0;
    $totalRefunded = 0;
    
    foreach ($allStatsRecords as $record) {
        $totalRecords++;
        
        // 根据状态分类统计
        if ($record['refund_status'] == 1 || $record['pay_status'] == 4) {
            $totalRefunded++;
            $totalRefund += $record['refund_amount'];
        } elseif ($record['pay_status'] == 1 && $record['refund_status'] == null) {
            // 只统计有效已支付且没有退款的记录
            $totalPaid++;
            $totalAmount += $record['amount'];
        } elseif ($record['form_status'] == 0) {
            $totalWaiting++;
        } elseif ($record['form_status'] == 5) {
            $totalExpired++;
        }
    }

} catch (PDOException $e) {
    die("数据库连接错误: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>缴费记录查询</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .header {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .card {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 18px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
            transition: all 0.3s ease;
        }
        .card:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.18);
        }
        
        /* 图表样式优化 */
        .bg-gradient-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            border: none !important;
        }
        
        .chart-container {
            background: #fff;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            border: 1px solid rgba(0, 0, 0, 0.05);
        }
        
        .chart-container:hover {
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
            transform: translateY(-3px);
        }
        
        .chart-header {
            border-bottom: 2px solid #f8f9fa;
            padding-bottom: 15px;
            margin-bottom: 20px !important;
        }
        
        /* 图表动画效果 */
        .chart-container canvas {
            transition: all 0.3s ease;
        }
        
        /* 统计卡片样式 */
        .stats-card {
            transition: all 0.3s ease;
            border: none !important;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
        }
        
        /* 表格样式优化 */
        .table-hover tbody tr:hover {
            background-color: #f8f9fa !important;
            transform: scale(1.01);
            transition: all 0.2s ease;
        }
        
        /* 按钮样式优化 */
        .btn {
            transition: all 0.3s ease;
            border-radius: 10px !important;
            font-weight: 500;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }
        
        /* 状态筛选按钮美化 */
        .btn-check:checked + .btn {
            transform: scale(1.05);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.25) !important;
            border-width: 2px !important;
        }
        
        .btn-check:checked + .btn-primary {
            background: linear-gradient(135deg, #0056b3 0%, #003d82 100%) !important;
            border-color: #0056b3 !important;
        }
        
        .btn-check:checked + .btn-success {
            background: linear-gradient(135deg, #198754 0%, #0f5132 100%) !important;
            border-color: #198754 !important;
        }
        
        .btn-check:checked + .btn-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%) !important;
            border-color: #ffc107 !important;
        }
        
        .btn-check:checked + .btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #a71e2a 100%) !important;
            border-color: #dc3545 !important;
        }
        
        /* 状态筛选按钮悬停效果 */
        .btn-check + .btn:hover {
            transform: translateY(-3px) scale(1.02);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        }
        
        /* 卡片阴影效果 */
        .card {
            border: none !important;
            border-radius: 18px !important;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
            transition: all 0.3s ease;
        }
        
        .card:hover {
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.18);
        }
        
        /* 响应式图表 */
        @media (max-width: 768px) {
            .chart-container {
                height: 280px !important;
                margin: 10px 0;
            }
            
            .card-body {
                padding: 20px !important;
            }
        }
        
        /* 加载动画 */
        .chart-loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 320px;
            background: linear-gradient(90deg, #f0f0f0 25%, transparent 25%, transparent 75%, #f0f0f0 75%, #f0f0f0),
                        linear-gradient(90deg, #f0f0f0 25%, transparent 25%, transparent 75%, #f0f0f0 75%, #f0f0f0);
            background-size: 20px 20px;
            background-position: 0 0, 0 10px;
            animation: loading 1s linear infinite;
        }
        
        @keyframes loading {
            0% { background-position: 0 0, 0 10px; }
            100% { background-position: 20px 0, 20px 10px; }
        }
        
        /* 图表标题样式 */
        .fw-bold {
            font-weight: 600 !important;
        }
        
        .text-primary {
            color: #667eea !important;
        }
        
        .text-success {
            color: #28a745 !important;
        }
        
        .table-container {
            max-height: 700px;
            overflow-y: auto;
            border-radius: 12px;
        }
        .table {
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }
        .table th {
            background: linear-gradient(135deg, #4a6bdf 0%, #6c5ce7 100%);
            color: white;
            position: sticky;
            top: 0;
            z-index: 10;
            font-weight: 600;
            padding: 16px 12px;
            border: none;
        }
        .table td {
            padding: 14px 12px;
            vertical-align: middle;
            border-bottom: 1px solid #e9ecef;
        }
        .table tr:hover td {
            background-color: #f8f9fa;
        }
        .status-paid {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        .status-refunded {
            background: linear-gradient(45deg, #dc3545, #fd7e14);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        .status-waiting {
            background: linear-gradient(45deg, #e67e22, #d35400);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            border: 1px solid #bdc3c7;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .status-expired {
            background: linear-gradient(45deg, #6c757d, #495057);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        .status-unknown {
            background: linear-gradient(45deg, #6610f2, #6f42c1);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        .amount {
            font-weight: bold;
            color: #28a745;
            font-size: 1.1em;
        }
        .search-box {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 15px;
            padding: 20px;
            border: 1px solid rgba(0, 0, 0, 0.08);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
        }
        .stats-card {
            text-align: center;
            padding: 25px 20px;
            border-radius: 18px;
            background: linear-gradient(135deg, #4a6bdf 0%, #6c5ce7 100%);
            color: white;
            box-shadow: 0 8px 25px rgba(74, 107, 223, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .stats-number {
            font-size: 2.8rem;
            font-weight: bold;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
        .user-info {
            min-width: 120px;
        }
        .mobile-info {
            min-width: 110px;
        }
        .nickname-info {
            min-width: 100px;
        }
        .text-primary-gradient {
            background: linear-gradient(135deg, #4a6bdf 0%, #6c5ce7 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        .form-control, .form-select {
            border-radius: 12px;
            border: 1px solid #dee2e6;
            padding: 12px 16px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        .form-control:focus, .form-select:focus {
            border-color: #4a6bdf;
            box-shadow: 0 0 0 0.2rem rgba(74, 107, 223, 0.25);
        }
        .btn-group .btn {
            border-radius: 6px;
            margin-right: 4px;
            font-weight: 500;
        }
        .btn-group .btn.active {
            background-color: #4a6bdf;
            border-color: #4a6bdf;
            color: white;
        }
        .btn-group .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
        }
        
        /* 增大日历选择器样式 */
        input[type="date"] {
            font-size: 16px;
            padding: 14px;
            height: 50px;
        }
        
        /* 日历弹出框样式 - 针对Webkit浏览器 */
        input[type="date"]::-webkit-calendar-picker-indicator {
            font-size: 20px;
            padding: 8px;
            cursor: pointer;
        }
        
        /* 日历弹出框容器 */
        input[type="date"]::-webkit-datetime-edit {
            font-size: 16px;
            padding: 8px;
        }
        
        /* 日历弹出框 */
        input[type="date"]:focus::-webkit-calendar-picker-indicator,
        input[type="date"]:hover::-webkit-calendar-picker-indicator {
            transform: scale(1.2);
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <!-- 头部 -->
        <div class="header p-4 mb-4 text-center">
            <h1 class="display-4 fw-bold text-primary mb-2">
                <i class="bi bi-cash-coin me-2"></i>
                缴费记录查询系统
            </h1>
            <p class="lead text-muted">实时查看所有已支付的缴费记录</p>
        </div>

        <!-- 统计信息 -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="stats-card">
                    <i class="bi bi-currency-yen fs-1 mb-2"></i>
                    <div class="stats-number">¥<?php echo number_format($totalPaidAmount, 2); ?></div>
                    <div>总缴费金额</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #20bf6b 0%, #01baef 100%);">
                    <i class="bi bi-check-circle-fill fs-1 mb-2"></i>
                    <div class="stats-number"><?php echo $totalPaidCount; ?> 笔</div>
                    <div>已支付</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);">
                    <i class="bi bi-clock-fill fs-1 mb-2"></i>
                    <div class="stats-number"><?php echo $totalWaitingCount; ?> 笔</div>
                    <div>未缴费</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
                    <i class="bi bi-exclamation-circle-fill fs-1 mb-2"></i>
                    <div class="stats-number"><?php echo $totalExpiredCount; ?> 笔</div>
                    <div>过期未缴</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);">
                    <i class="bi bi-arrow-return-left fs-1 mb-2"></i>
                    <div class="stats-number"><?php echo $totalRefundedCount; ?> 笔</div>
                    <div>已退款</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
                    <i class="bi bi-people-fill fs-1 mb-2"></i>
                    <div class="stats-number"><?php echo $totalRecordsCount; ?> 笔</div>
                    <div>总记录数</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #343a40 0%, #212529 100%);">
                    <i class="bi bi-cash-coin fs-1 mb-2"></i>
                    <div class="stats-number">¥<?php echo number_format($totalRefundAmount, 2); ?></div>
                    <div>总退款金额</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);">
                    <i class="bi bi-person-plus-fill fs-1 mb-2"></i>
                    <div class="stats-number"><?php echo $todaySignupCount; ?> 人</div>
                    <div><?php echo !empty($startDate) ? htmlspecialchars($startDate) : '当日'; ?>报名人数</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
                    <i class="bi bi-currency-yen fs-1 mb-2"></i>
                    <div class="stats-number"><?php echo $todayPaidCount; ?> 人</div>
                    <div><?php echo !empty($startDate) ? htmlspecialchars($startDate) : '当日'; ?>缴费人数</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #20c997 0%, #17a2b8 100%);">
                    <i class="bi bi-wallet2 fs-1 mb-2"></i>
                    <div class="stats-number">¥<?php echo number_format($todayPaidAmount, 2); ?></div>
                    <div><?php echo !empty($startDate) ? htmlspecialchars($startDate) : '当日'; ?>缴费金额</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);">
                    <i class="bi bi-person-dash-fill fs-1 mb-2"></i>
                    <div class="stats-number"><?php echo $todayRefundCount; ?> 人</div>
                    <div><?php echo !empty($startDate) ? htmlspecialchars($startDate) : '当日'; ?>退费人数</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #fd7e14 0%, #ffc107 100%);">
                    <i class="bi bi-arrow-return-left fs-1 mb-2"></i>
                    <div class="stats-number">¥<?php echo number_format($todayRefundAmount, 2); ?></div>
                    <div><?php echo !empty($startDate) ? htmlspecialchars($startDate) : '当日'; ?>退费金额</div>
                </div>
            </div>
        </div>

        <!-- 最近10天统计图表 -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-gradient-primary text-white">
                        <h5 class="mb-0"><i class="bi bi-graph-up me-2"></i>最近10天统计图表</h5>
                    </div>
                    <div class="card-body p-4">
                        <div class="row">
                            <div class="col-md-6 mb-4 mb-md-0">
                                <div class="chart-header text-center mb-3">
                                    <h6 class="fw-bold text-primary">
                                        <i class="bi bi-people-fill me-2"></i>人数统计趋势
                                    </h6>
                                </div>
                                <div class="chart-container" style="position: relative; height: 320px;">
                                    <canvas id="countChart"></canvas>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="chart-header text-center mb-3">
                                    <h6 class="fw-bold text-success">
                                        <i class="bi bi-currency-yen me-2"></i>金额统计趋势
                                    </h6>
                                </div>
                                <div class="chart-container" style="position: relative; height: 320px;">
                                    <canvas id="amountChart"></canvas>
                                </div>
                            </div>
                        </div>
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="text-center">
                                    <small class="text-muted">
                                        <i class="bi bi-info-circle me-1"></i>
                                        数据更新时间: <?php echo date('Y-m-d H:i:s'); ?> | 
                                        统计周期: 最近10天 (<?php echo date('m-d', strtotime('-9 days')); ?> ~ <?php echo date('m-d'); ?>)
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="card mb-4" style="margin-top: 40px;">
            <div class="card-body">
                <form method="GET" action="" id="filterForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="search-box">
                                <h5><i class="bi bi-search me-2"></i>快速搜索</h5>
                                <input type="text" id="searchInput" class="form-control" placeholder="搜索姓名、手机号、课程...">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="search-box">
                                <h5><i class="bi bi-calendar me-2"></i>日期筛选</h5>
                                <div class="input-group">
                                    <input type="date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($startDate); ?>" min="2025-11-05" max="<?php echo date('Y-m-d'); ?>">
                                    <?php if (!empty($startDate)): ?>
                                    <button type="button" class="btn btn-outline-secondary" onclick="clearDateAndReset()" title="清除日期">
                                        <i class="bi bi-x"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                                <small class="text-muted mt-1 d-block">
                                    <?php echo empty($startDate) ? '日期未选' : htmlspecialchars($startDate); ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 状态筛选选项卡 - 美化版 -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <!-- 查询条数显示 - 放在顶部 -->
                            <div class="text-center mb-3">
                                <div class="alert alert-primary border-0 shadow-sm" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                    <h4 class="mb-0">
                                        <i class="bi bi-list-check me-2"></i>
                                        本次查询到: <span class="fw-bold"><?php echo count($records); ?></span> 条记录
                                    </h4>
                                </div>
                            </div>
                            
                            <h5 class="mb-3 text-center"><i class="bi bi-funnel me-2"></i>状态筛选</h5>
                            <div class="row justify-content-center">
                                <div class="col-auto mb-2">
                                    <input type="radio" class="btn-check" name="status" id="status-all" value="" autocomplete="off" <?php echo empty($statusFilter) ? 'checked' : ''; ?>>
                                    <label class="btn btn-lg btn-primary rounded-pill px-4 py-2 shadow-sm" for="status-all" style="min-width: 100px;">
                                        <i class="bi bi-grid-3x3-gap-fill me-1"></i>全部
                                    </label>
                                </div>
                                
                                <div class="col-auto mb-2">
                                    <input type="radio" class="btn-check" name="status" id="status-paid" value="paid" autocomplete="off" <?php echo $statusFilter === 'paid' ? 'checked' : ''; ?>>
                                    <label class="btn btn-lg btn-success rounded-pill px-4 py-2 shadow-sm" for="status-paid" style="min-width: 100px;">
                                        <i class="bi bi-check-circle-fill me-1"></i>已支付
                                    </label>
                                </div>
                                
                                <div class="col-auto mb-2">
                                    <input type="radio" class="btn-check" name="status" id="status-waiting" value="waiting" autocomplete="off" <?php echo $statusFilter === 'waiting' ? 'checked' : ''; ?>>
                                    <label class="btn btn-lg btn-warning rounded-pill px-4 py-2 shadow-sm" for="status-waiting" style="min-width: 100px;">
                                        <i class="bi bi-clock-fill me-1"></i>未缴费
                                    </label>
                                </div>
                                
                                <div class="col-auto mb-2">
                                    <input type="radio" class="btn-check" name="status" id="status-refunded" value="refunded" autocomplete="off" <?php echo $statusFilter === 'refunded' ? 'checked' : ''; ?>>
                                    <label class="btn btn-lg btn-danger rounded-pill px-4 py-2 shadow-sm" for="status-refunded" style="min-width: 100px;">
                                        <i class="bi bi-arrow-return-left-fill me-1"></i>已退款
                                    </label>
                                </div>
                            </div>
                            
                            <!-- SQL语句显示 -->
                            <div class="mt-2">
                                <button type="button" class="btn btn-outline-info btn-sm" data-bs-toggle="collapse" data-bs-target="#sqlQuery">
                                    <i class="bi bi-code-slash me-1"></i>
                                    查看SQL查询语句
                                </button>
                                <div class="collapse mt-2" id="sqlQuery">
                                    <div class="card card-body bg-light">
                                        <small class="text-muted">
                                            <strong>执行的SQL查询:</strong><br>
                                            <?php 
                                            $displaySql = $sql;
                                            foreach ($params as $key => $value) {
                                                $displaySql = str_replace($key, "'" . $value . "'", $displaySql);
                                            }
                                            echo htmlspecialchars($displaySql); 
                                            ?>
                                            
                                            <br><br><strong>当日报名人数SQL:</strong><br>
                                            <?php 
                                            $displayTodaySignupSql = $todaySignupSql;
                                            $displayTodaySignupSql = str_replace(':today', "'" . $targetDate . "'", $displayTodaySignupSql);
                                            echo htmlspecialchars($displayTodaySignupSql); 
                                            ?>
                                            
                                            <br><br><strong>当日缴费人数SQL:</strong><br>
                                            <?php 
                                            $displayTodayPaidSql = $todayPaidSql;
                                            $displayTodayPaidSql = str_replace(':today', "'" . $targetDate . "'", $displayTodayPaidSql);
                                            echo htmlspecialchars($displayTodayPaidSql); 
                                            ?>
                                            
                                            <br><br><strong>当日缴费金额SQL:</strong><br>
                                            <?php 
                                            $displayTodayPaidAmountSql = $todayPaidAmountSql;
                                            $displayTodayPaidAmountSql = str_replace(':today', "'" . $targetDate . "'", $displayTodayPaidAmountSql);
                                            echo htmlspecialchars($displayTodayPaidAmountSql); 
                                            ?>
                                            
                                            <br><br><strong>当日退费人数SQL:</strong><br>
                                            <?php 
                                            $displayTodayRefundCountSql = $todayRefundCountSql;
                                            $displayTodayRefundCountSql = str_replace(':today', "'" . $targetDate . "'", $displayTodayRefundCountSql);
                                            echo htmlspecialchars($displayTodayRefundCountSql); 
                                            ?>
                                            
                                            <br><br><strong>当日退费金额SQL:</strong><br>
                                            <?php 
                                            $displayTodayRefundAmountSql = $todayRefundAmountSql;
                                            $displayTodayRefundAmountSql = str_replace(':today', "'" . $targetDate . "'", $displayTodayRefundAmountSql);
                                            echo htmlspecialchars($displayTodayRefundAmountSql); 
                                            ?>
                                            
                                            <br><br><strong>已退款总人数SQL:</strong><br>
                                            <?php 
                                            $displayTotalRefundedSql = "SELECT COUNT(DISTINCT f.user_id) as count \n";
                                            $displayTotalRefundedSql .= "FROM `eb_apply_form_item` as f \n";
                                            $displayTotalRefundedSql .= "LEFT JOIN fa_order o ON o.id = f.order_id \n";
                                            $displayTotalRefundedSql .= "WHERE (o.refund_status = 1 OR o.pay_status = 4)";
                                            if (!empty($statusFilter) && $statusFilter !== 'refunded') {
                                                // 如果当前有状态筛选但不是退款状态，添加额外条件
                                                if ($statusFilter === 'paid') {
                                                    $displayTotalRefundedSql .= " AND o.pay_status = 1 AND o.refund_status IS NULL";
                                                } elseif ($statusFilter === 'waiting') {
                                                    $displayTotalRefundedSql .= " AND f.status = 0";
                                                }
                                            }
                                            echo htmlspecialchars($displayTotalRefundedSql); 
                                            ?>
                                            
                                            <br><br><strong>总退款金额SQL:</strong><br>
                                            <?php 
                                            $displayTotalRefundAmountSql = "SELECT SUM(o.refund_amount) as total_refund \n";
                                            $displayTotalRefundAmountSql .= "FROM `eb_apply_form_item` as f \n";
                                            $displayTotalRefundAmountSql .= "LEFT JOIN fa_order o ON o.id = f.order_id \n";
                                            $displayTotalRefundAmountSql .= "WHERE (o.refund_status = 1 OR o.pay_status = 4)";
                                            if (!empty($statusFilter) && $statusFilter !== 'refunded') {
                                                // 如果当前有状态筛选但不是退款状态，添加额外条件
                                                if ($statusFilter === 'paid') {
                                                    $displayTotalRefundAmountSql .= " AND o.pay_status = 1 AND o.refund_status IS NULL";
                                                } elseif ($statusFilter === 'waiting') {
                                                    $displayTotalRefundAmountSql .= " AND f.status = 0";
                                                }
                                            }
                                            echo htmlspecialchars($displayTotalRefundAmountSql); 
                                            ?>
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-12">
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearDateAndReset()">
                                <i class="bi bi-x-circle me-1"></i>清除日期
                            </button>
                            <button type="button" class="btn btn-outline-warning btn-sm ms-2" onclick="location.href='jaofeiqingkuang.php'">
                                <i class="bi bi-arrow-clockwise me-1"></i>重置全部
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 数据表格 -->
        <div class="card">
            <div class="card-header">
                <h4 class="mb-0">
                    <i class="bi bi-list-check me-2"></i>
                    缴费记录列表
                </h4>
            </div>
            <div class="card-body">
                <div class="table-container">
                    <table class="table table-hover table-striped" id="recordsTable">
                        <thead>
                            <tr>
                                <th><i class="bi bi-person"></i> 用户名</th>
                                <th><i class="bi bi-chat-heart"></i> 昵称</th>
                                <th><i class="bi bi-phone"></i> 手机号</th>
                                <th><i class="bi bi-book"></i> 课程名称</th>
                                <th><i class="bi bi-card-text"></i> 缴费说明</th>
                                <th><i class="bi bi-currency-yen"></i> 金额</th>
                                <th><i class="bi bi-clock"></i> 缴费时间</th>
                                <th><i class="bi bi-info-circle"></i> 状态</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($records)): ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-4">
                                        <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                                        暂无缴费记录
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($records as $record): ?>
                                    <?php 
                                    // 状态判断逻辑
                                    if ($record['refund_status'] == 1) {
                                        $statusClass = 'status-refunded';
                                        $statusText = '已退款';
                                    } elseif ($record['pay_status'] == 4) {
                                        $statusClass = 'status-refunded';
                                        $statusText = '已退款';
                                    } elseif ($record['pay_status'] == 1) {
                                        $statusClass = 'status-paid';
                                        $statusText = '已支付';
                                    } elseif ($record['form_status'] == 0) {
                                        $statusClass = 'status-waiting';
                                        $statusText = '未缴费';
                                    } elseif ($record['form_status'] == 5) {
                                        $statusClass = 'status-expired';
                                        $statusText = '过期未缴';
                                    } else {
                                        $statusClass = 'status-unknown';
                                        $statusText = '未知状态';
                                    }
                                    ?>
                                    <tr>
                                        <td class="user-info">
                                            <span class="fw-bold text-primary"><?php echo htmlspecialchars($record['username'] ?? '未设置'); ?></span>
                                        </td>
                                        <td class="nickname-info">
                                            <?php if (!empty($record['nickname'])): ?>
                                                <span class="badge bg-info text-white"><?php echo htmlspecialchars($record['nickname']); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">无昵称</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="mobile-info">
                                            <?php if (!empty($record['mobile'])): ?>
                                                <span class="fw-semibold"><?php echo htmlspecialchars($record['mobile']); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">未设置</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($record['class_name'] ?? '未知课程'); ?></td>
                                        <td><?php echo htmlspecialchars($record['intro'] ?? '无说明'); ?></td>
                                        <td class="amount">¥<?php echo number_format($record['amount'], 2); ?></td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($record['create_time'])); ?></td>
                                        <td>
                                            <span class="badge rounded-pill <?php echo $statusClass; ?> p-2">
                                                <i class="bi <?php echo $record['refund_status'] == 1 ? 'bi-arrow-return-left' : 'bi-check-circle'; ?> me-1"></i>
                                                <?php echo $statusText; ?>
                                                <?php if ($record['refund_status'] == 1): ?>
                                                    <br><small>退款: ¥<?php echo number_format($record['refund_amount'], 2); ?></small>
                                                <?php endif; ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer text-muted">
                <small>最后更新时间: <?php echo date('Y-m-d H:i:s'); ?></small>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 搜索功能
        document.getElementById('searchInput').addEventListener('input', function() {
            const searchText = this.value.toLowerCase();
            const rows = document.querySelectorAll('#recordsTable tbody tr');
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchText) ? '' : 'none';
            });
        });



        // 自动刷新页面（每5分钟）
        setInterval(() => {
            if (!document.hidden) {
                location.reload();
            }
        }, 300000);
        
        // 状态选项卡切换效果 - 点击后立即提交表单
        document.querySelectorAll('input[name="status"]').forEach(radio => {
            radio.addEventListener('change', function() {
                document.querySelectorAll('.btn-group .btn').forEach(btn => {
                    btn.classList.remove('active');
                });
                document.querySelector(`label[for="${this.id}"]`).classList.add('active');
                // 立即提交表单
                document.getElementById('filterForm').submit();
            });
        });
        
        // 日期选择器点击事件 - 确保点击日期输入框时弹出日历
        document.querySelector('input[type="date"]').addEventListener('click', function() {
            this.showPicker();
        });
        
        // 日期选择器焦点事件 - 确保获得焦点时也弹出日历
        document.querySelector('input[type="date"]').addEventListener('focus', function() {
            this.showPicker();
        });
        
        // 日期选择器改变时也自动提交表单
        document.querySelector('input[name="start_date"]').addEventListener('change', function() {
            document.getElementById('filterForm').submit();
        });
        
        // 清除日期功能
        function clearDateAndReset() {
            // 清除日期输入框的值
            document.querySelector('input[name="start_date"]').value = '';
            // 提交表单以应用新的筛选条件
            document.getElementById('filterForm').submit();
        }
    </script>
    <!-- Chart.js 多CDN备份加载 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>
    <script>
        // Chart.js 加载状态检查和备用方案
        function checkChartJsLoaded() {
            if (typeof Chart === 'undefined') {
                console.warn('Chart.js 未从 jsDelivr CDN 加载成功，尝试备用CDN...');
                document.write('<script src="https://unpkg.com/chart.js@4.4.0/dist/chart.umd.js"><\/script>');
                return false;
            }
            console.log('Chart.js 已成功从 jsDelivr CDN 加载');
            return true;
        }
        
        // 立即检查加载状态
        var chartJsLoaded = checkChartJsLoaded();
        
        // 3秒后再次检查，如果还是失败则显示详细错误信息
        setTimeout(function() {
            if (typeof Chart === 'undefined') {
                console.error('Chart.js 所有CDN加载失败！使用的CDN地址：');
                console.error('1. https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js');
                console.error('2. https://unpkg.com/chart.js@4.4.0/dist/chart.umd.js');
                console.error('请检查网络连接或使用本地Chart.js文件');
                
                // 显示详细的错误提示
                var chartContainers = document.querySelectorAll('.chart-container');
                chartContainers.forEach(function(container) {
                    container.innerHTML = '<div class="alert alert-danger text-center p-4">' +
                        '<i class="bi bi-exclamation-triangle fs-1 d-block mb-2"></i>' +
                        '<h5 class="mb-2">图表库加载失败</h5>' +
                        '<p class="mb-2">使用的CDN地址：</p>' +
                        '<small class="d-block text-muted mb-1">• https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js</small>' +
                        '<small class="d-block text-muted">• https://unpkg.com/chart.js@4.4.0/dist/chart.umd.js</small>' +
                        '<p class="mt-3 mb-0">请检查网络连接或联系管理员添加本地Chart.js文件</p>' +
                        '</div>';
                });
            }
        }, 3000);
    </script>
    <script>
        // 图表加载动画
        function showChartLoading() {
            const containers = document.querySelectorAll('.chart-container');
            containers.forEach(container => {
                // 只在没有加载动画时添加，避免覆盖canvas元素
                if (!container.querySelector('.chart-loading')) {
                    const loadingDiv = document.createElement('div');
                    loadingDiv.className = 'chart-loading';
                    loadingDiv.innerHTML = '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div>';
                    container.appendChild(loadingDiv);
                }
            });
        }
        
        function hideChartLoading() {
            const containers = document.querySelectorAll('.chart-container');
            containers.forEach(container => {
                // 移除加载动画，但保留原有的canvas元素
                const loadingDiv = container.querySelector('.chart-loading');
                if (loadingDiv) {
                    loadingDiv.remove();
                }
                
                // 确保canvas元素可见
                const canvas = container.querySelector('canvas');
                if (canvas) {
                    canvas.style.display = 'block';
                }
            });
        }
        
        // 显示加载动画
        showChartLoading();
        
        // 使用DOMContentLoaded确保DOM完全加载后再初始化图表
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                // 延迟加载图表，提供更好的用户体验
                setTimeout(() => {
                    hideChartLoading();
                    initializeCharts();
                }, 800);
            });
        } else {
            // DOM已经加载完成，直接执行
            setTimeout(() => {
                hideChartLoading();
                initializeCharts();
            }, 800);
        }
        
        function initializeCharts() {
            try {
                // 检查Chart.js是否加载成功
                if (typeof Chart === 'undefined') {
                    throw new Error('Chart.js 库未加载成功');
                }
                
                // 检查canvas元素是否存在
                const countCanvas = document.getElementById('countChart');
                const amountCanvas = document.getElementById('amountChart');
                
                if (!countCanvas || !amountCanvas) {
                    throw new Error('图表容器未找到，请刷新页面重试');
                }
                
                // 准备图表数据
                const chartData = <?php echo json_encode($last10DaysStats); ?>;
                const labels = chartData.map(item => item.date);
                
                // 图表默认配置
                Chart.defaults.font.family = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
                Chart.defaults.font.size = 12;
                Chart.defaults.color = '#495057';
                
                // 人数统计图表
                const countCtx = countCanvas.getContext('2d');
                new Chart(countCtx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: '报名人数',
                    data: chartData.map(item => item.signup_count),
                    borderColor: '#17a2b8',
                    backgroundColor: 'rgba(23, 162, 184, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: '#17a2b8',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 6,
                    pointHoverRadius: 8
                }, {
                    label: '缴费人数',
                    data: chartData.map(item => item.paid_count),
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: '#28a745',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 6,
                    pointHoverRadius: 8
                }, {
                    label: '退费人数',
                    data: chartData.map(item => item.refund_count),
                    borderColor: '#dc3545',
                    backgroundColor: 'rgba(220, 53, 69, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: '#dc3545',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 6,
                    pointHoverRadius: 8
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '最近10天人数统计趋势',
                        font: {
                            size: 16,
                            weight: 'bold'
                        },
                        padding: 20
                    },
                    legend: {
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: '#fff',
                        borderWidth: 1,
                        cornerRadius: 6,
                        displayColors: true,
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': ' + context.parsed.y + ' 人';
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: true,
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            font: {
                                size: 11
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            display: true,
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            stepSize: 1,
                            font: {
                                size: 11
                            },
                            callback: function(value) {
                                return value + ' 人';
                            }
                        }
                    }
                },
                interaction: {
                    mode: 'nearest',
                    axis: 'x',
                    intersect: false
                }
            }
        });
        
        // 金额统计图表
        const amountCtx = amountCanvas.getContext('2d');
        new Chart(amountCtx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: '报名金额',
                    data: chartData.map(item => item.signup_amount),
                    borderColor: '#6f42c1',
                    backgroundColor: 'rgba(111, 66, 193, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: '#6f42c1',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 6,
                    pointHoverRadius: 8
                }, {
                    label: '缴费金额',
                    data: chartData.map(item => item.paid_amount),
                    borderColor: '#fd7e14',
                    backgroundColor: 'rgba(253, 126, 20, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: '#fd7e14',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 6,
                    pointHoverRadius: 8
                }, {
                    label: '退费金额',
                    data: chartData.map(item => item.refund_amount),
                    borderColor: '#e83e8c',
                    backgroundColor: 'rgba(232, 62, 140, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: '#e83e8c',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 6,
                    pointHoverRadius: 8
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '最近10天金额统计趋势',
                        font: {
                            size: 16,
                            weight: 'bold'
                        },
                        padding: 20
                    },
                    legend: {
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: '#fff',
                        borderWidth: 1,
                        cornerRadius: 6,
                        displayColors: true,
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': ¥' + context.parsed.y.toLocaleString();
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: true,
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            font: {
                                size: 11
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            display: true,
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            font: {
                                size: 11
                            },
                            callback: function(value) {
                                return '¥' + value.toLocaleString();
                            }
                        }
                    }
                },
                interaction: {
                    mode: 'nearest',
                    axis: 'x',
                    intersect: false
                }
            }
        });
        
        // 添加图表动画效果
        setTimeout(() => {
            // 可以在这里添加额外的动画效果
            console.log('图表加载完成');
        }, 1000);
        
            } catch (error) {
                console.error('图表初始化失败:', error);
                // 显示友好的错误提示
                var chartContainers = document.querySelectorAll('.chart-container');
                chartContainers.forEach(function(container) {
                    container.innerHTML = '<div class="text-center text-muted p-5"><i class="bi bi-exclamation-triangle fs-1"></i><p class="mt-3">图表加载失败：' + error.message + '</p></div>';
                });
            }
        }
    </script>
</body>
</html>